package cn.jietuo.first.class03;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/6/20
 * @description: 归并排序
 */
public class Code01_MergeSort {

    public static void process(int[] arr, int l, int r) {
        if (l == r) {
            return;
        }
        // 找出中点
        int mid = l + ((r - l) >> 1);
        process(arr, l, mid);
        process(arr, mid + 1, r);
        merge(arr, l, mid, r);
    }

    private static void merge(int[] arr, int l, int m, int r) {
        // 构建一个help数组，和需要排序数组大小相等
        int[] help = new int[r - l + 1];
        int p1 = l;
        int p2 = m + 1;
        int i = 0;
        while (p1 <= m && p2 <= r) {
            help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= m) {
            help[i++] = arr[p1++];
        }
        while (p2 <= r) {
            help[i++] = arr[p2++];
        }
        for (int j = 0; j < help.length; j++) {
            arr[l + j] = help[j];
        }
    }

    /**
     * 不用递归的版本
     * @param arr
     */
    private static void mergeSort2(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        int n = arr.length - 1;
        // 当前有序的左数组长度
        int mergeSize = 1;
        while (mergeSize < n) {
            int l = 0;
            while (l < n) {
                int m = l + mergeSize -1;
                if (m > n) {
                    break;
                }
                int r = Math.min(m + mergeSize, n -1);
                merge(arr, l, m, r);
                l = r + 1;
            }

            if (mergeSize > n / 2) {
                return;
            }
            mergeSize = mergeSize << 1;
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{2, 4, 6, 1, 4, 7, 8, 20, 21};
//        process(arr, 0, arr.length - 1);
        mergeSort2(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
